// 发布订阅模式

// Observer类
class Observer {
  caches = {};

  // 订阅事件
  on (eventName, fn){
    this.caches[eventName] = this.caches[eventName] || [];
    this.caches[eventName].push(fn);
  }

  // 发布事件
  emit (eventName, data) {
    if (this.caches[eventName]) {
      this.caches[eventName].forEach(fn => fn(data));
    }
  }

  // 取消订阅
  off (eventName, fn) {
    if (this.caches[eventName]) {
      const newCaches = fn ? this.caches[eventName].filter(e => e !== fn) : [];
      this.caches[eventName] = newCaches;
    }
  }
}

// 测试
const ob = new Observer();
let l1 = (data) => console.log(`l1_${data}`)
let l2 = (data) => console.log(`l2_${data}`)
ob.on('event1',l1)
ob.on('event1',l2)
ob.emit('event1',789)
ob.off('event1',l1)
ob.emit('event1',567)